package be.phl.obstacleapp;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import be.phl.model.DBAdapterUser;
import be.phl.model.SHA1;
import be.phl.webservice.User;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {

	/**
	 * set up static variables
	 */
	private static final String SERVER_URL = MainData.getServerUrl() + "/login";
	private static final String TAG = "LoginActivity";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private LoginTask mAuthTask = null;

	// Values for username and password at the time of the login attempt.
	private String mUsername;
	private String mPassword;

	// UI references.
	private EditText mUserNameView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;
	private TextView mConnectionError;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);

		mConnectionError = (TextView) findViewById(R.id.connection_error);
		// Set up the login form.
		// mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
		mUserNameView = (EditText) findViewById(R.id.userName);
		// mEmailView.setText(mEmail);

		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});

		mUserNameView.setText("obstacleadmin");
		mPasswordView.setText("5F93ET7CB");

		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.activity_login, menu);
		return true;
	}

	/**
	 * Attempts to sign in the account specified by the login form. If there are
	 * form errors (invalid username, missing fields, etc.), the errors are
	 * presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		mUserNameView.setError(null);
		mPasswordView.setError(null);
		mConnectionError.setVisibility(View.GONE);

		// Store values at the time of the login attempt.
		mUsername = mUserNameView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 3) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mUsername)) {
			mUserNameView.setError(getString(R.string.error_field_required));
			focusView = mUserNameView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);

			showProgress(true);

			String mPasswordHash = null;
			try {
				mPasswordHash = SHA1.SHA1(mUsername.toUpperCase() + mPassword);
			} catch (NoSuchAlgorithmException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			UserLogin(mUsername, mPasswordHash);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	private void UserLogin(String userName, String password) {

		int userError = 0;
		User u = null;
		boolean userExists = false;
		DBAdapterUser db = new DBAdapterUser(this);
		db.open();
		// get a list of all the users in the database
		Cursor c = db.getAllUsers();
		// check if the user exists
		if (c.moveToFirst()) {
			do {
				if (userName.equals(c.getString(1))) {
					u = new User();
					u.setId(c.getInt(0));
					u.setUserName(c.getString(1));
					u.setFirstName(c.getString(2));
					u.setLastName(c.getString(3));
					u.setPassWord(c.getString(4));
					u.setEmail(c.getString(5));
					u.setUserFunction(c.getInt(6));
					try {
						u.setDayOfBirth(MainData.getDateformat().parse(
								c.getString(7)));
						Log.i(TAG, u.getDayOfBirth().toString());
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					u.setAdmin(c.getString(8));
					u.setActivated(c.getString(9));
					userExists = true;
				}
			} while (c.moveToNext());
		}
		db.close();

		// check the users password
		if (userExists) {
			if (password.equals(u.getPassWord())) {
				Log.i(TAG, "logged on");
				MainData.setLoggedUser(u);
				Intent main = new Intent(this, MainActivity.class);
				startActivity(main);
				this.finish();
				return;

			} else {
				userError = 2;
			}
		} else {
			userError = 1;
		}

		// if the user isn't found local, the program will attempt to connect
		// online
		if (userError != 0) {
			if (MainData.isNetworkAvailable(this)) {

				mAuthTask = new LoginTask();
				mAuthTask.execute(new String[] { SERVER_URL + "/" + userName
						+ "/" + password });

				return;
			} else {
				mConnectionError.setVisibility(View.VISIBLE);
			}
		}

		// see wich error is made
		switch (userError) {
		case 1:
			mUserNameView.setError(getString(R.string.error_invalid_username));
			mUserNameView.requestFocus();
			break;
		case 2:
			mPasswordView
					.setError(getString(R.string.error_incorrect_password));
			mPasswordView.requestFocus();
			break;
		default:
			break;
		}

		showProgress(false);
	}

	/**
	 * Represents an asynchronous task to call the webservice
	 */
	public class LoginTask extends AsyncTask<String, Void, Boolean> {

		private static final String TAG = "UserLoginTask";

		ObjectMapper objectMapper = new ObjectMapper();

		@Override
		protected Boolean doInBackground(String... urls) {
			// TODO: attempt connect to a network service.

			Log.i(TAG, "Attempt connection to Webservice: " + urls[0]);
			try {
				// Create a new RestTemplate instance
				RestTemplate restTemplate = new RestTemplate();

				// set the mapper for parsing the json data
				objectMapper.configure(
						DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
						true);
				MappingJackson2HttpMessageConverter mapper = new MappingJackson2HttpMessageConverter();
				mapper.setObjectMapper(objectMapper);

				// Add the message converter
				restTemplate.getMessageConverters().add(mapper);
				((SimpleClientHttpRequestFactory) restTemplate
						.getRequestFactory()).setConnectTimeout(30 * 1000);

				// Make the HTTP GET request
				User result = restTemplate.getForObject(urls[0], User.class);

				if (result != null) {

					Log.i(TAG, "Connection succeeded");

					MainData.setLoggedUser(result);

					DBAdapterUser db = new DBAdapterUser(LoginActivity.this);
					db.open();
					db.insertOrUpdateUser(result);
					db.close();
					return true;

				}
			} catch (Exception ex) {
				Log.e(TAG, ex.getMessage());
			}

			// TODO: register the new account here.
			return false;
		}

		@Override
		protected void onPostExecute(final Boolean success) {

			mAuthTask = null;

			if (success) {
				Intent mainAct = new Intent(LoginActivity.this,
						MainActivity.class);
				LoginActivity.this.startActivity(mainAct);
				LoginActivity.this.finish();

			} else {
				showProgress(false);
				mUserNameView.setError(getString(R.string.error_invalid_login));
				mUserNameView.requestFocus();
			}
		}
	}
}
